import Vue from 'vue'
import {
  Message
} from 'element-ui'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Login from "../views/Login.vue"
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    redirect: '/user',
    children: [
      {
        path: '/user',
        meta: {
          title: '用户管理'
        },
        component: () => import('../components/User.vue')
      },
      {
        path: '/manage',
        meta: {
          title: '管理员管理'
        },
        component: () => import('../components/Manage.vue')
      },
      {
        path: '/help',
        meta: {
          title: '帮助管理'
        },
        component: () => import('../components/Help.vue')
      },
      {
        path: '/report',
        meta: {
          title: '举报管理'
        },
        component: () => import('../components/Report.vue')
      },
      {
        path: '/method',
        meta: {
          title: '官方攻略管理'
        },
        component: () => import('../components/Method.vue')
      },
      {
        path: '/essay',
        meta: {
          title: '用户提交攻略管理'
        },
        component: () => import('../components/Essay.vue')
      },
      {
        path: '/spot',
        meta: {
          title: '景点管理'
        },
        component: () => import('../components/Spot.vue')
      },
      {
        path: '/travel',
        meta: {
          title: '驴友管理'
        },
        component: () => import('../components/Travel.vue')
      },
      {
        path: '/comment',
        meta: {
          title: '评论管理'
        },
        component: () => import('../components/Comment.vue')
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  //修改界面title
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  let token = window.localStorage.getItem("token")
  const tokenStartTime = window.localStorage.getItem("tokenStartTime")
  // 六天过期：6*24*3600*1000
  const timeOver = 6 * 24 * 3600 * 1000
  // 10分钟过期
  // const timeOver = 600 * 1000
  let date = new Date().getTime()
  if (date - tokenStartTime > timeOver) {
    token = null
    sessionStorage.removeItem("activePath")
  }
  if (!token) {
    if (to.path == '/login') return next()
    Message.error("登陆状态过期，请重新登录")
    return next('/login')
  } else if (to.path == '/login') {
    return next('/user')
  }
  return next()
})

export default router
